import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Forget from '../views/forget.vue'

function hPage(n, t, role) {
  return {
    path: '/' + n,
    name: n,
    meta: {
      title: t,
      permission: role || false
    },
    component: () => import(`../views/${n}/page.vue`)
  }
}
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/index'
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        hPage('index', '主页'),
        hPage('UserData', '用户数据'),
        hPage('OriStructure', '组织架构'),
        hPage('OnlineStatistics', '在线统计'),
        hPage('Schoolinform', '学校信息'),
        hPage('DesktopManage', '桌面管理')
        // {
        //   path: '/index',
        //   name: 'index',
        //   meta: {
        //     title: '主页'
        //   },
        //   component: () => import('../views/index/page.vue')
        // },
      ]
    },
    {
      path: '/Login',
      name: 'Login',
      meta: {
        title: '登录'
      },
      component: () => import('../views/Login.vue')
    },
    {
      path: '/forget',
      name: 'forget',
      component: Forget,
    }
  ]
})
router.beforeEach((to, from, next) => {
  document.title = `${__projName}|${to.meta.title}`
  var tpath = to.path
  var fpath = from.path
  let role
  try {
    role = JSON.parse(localStorage.getItem('LocalData'))
    // console.log('role', role)
  } catch (e) {
    role = null
    //TODO handle the exception
  }
  let t = Date.now()
  // || role?.tm <= t
  if (role == null && tpath !== '/Login'&&tpath!=='/forget') {
    console.log('无权限请登录', role)
    next('/Login')
    // next();
  } else if (to.meta.permission) {
    // 如果是管理员权限则可进入
    console.log('后台设置', role)
    if (role.user.RoleName === 'system') {
      next()
    } else {
      alert('当前用户无设置权限')
      next(from.name) //哪里来哪里去
    }
  } else {
    if (tpath == '/Login' && fpath == '/index' && role != null) {
      // next('/index');
      location.reload()
    } else if (tpath == '/Login' && fpath != '/index' && role != null) {
      next('/index')
    } else {
      next()
    }
  }
})
export default router
